package com.axs.logcollector.utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

public class LogCollectorUtils {
	private static final Logger m_log = Logger.getLogger(LogCollectorUtils.class);
	
	public static final int BUFFER = 2048; 
	public static final String AMS_TMP_DIR = File.separator + "ams_log_file_dir";
	public static final String AMS_ZIP_DIR = File.separator + "ams_zip_file_dir";
			
	public static String getIpAddress(String nodeId) {
		String ipAddress = nodeId.split("=") [2];
		return ipAddress.split(":") [0];
	}
	
	public static List<String> convertToServerIpList(String nodeIds) {
		nodeIds = nodeIds.substring(1, nodeIds.length() - 2).replaceAll("\\s+", "");
		return Arrays.asList(nodeIds.split(","));
	}
	
	public static List<String> buildFullAmsLogDir(String amsLogDir, List<String> logNames) {
		List<String> amsFullLogDir = new ArrayList<String>();
		for (String logName : logNames) {
			amsFullLogDir.add(amsLogDir + "/" + logName);
		}
		return amsFullLogDir;
	}
	
	public static String getTmpLogFileDir() {
		String tmpDir = System.getenv("TMP") + AMS_TMP_DIR;
		File file = new File(tmpDir);
		if (!file.exists()) {
			m_log.info("Creating tmp dir: " + tmpDir);
			file.mkdir();
		}
		return tmpDir;
	}
	
	public static String getTmpZipFileDir() {
		String zipDir = System.getenv("TMP") + File.separator + AMS_ZIP_DIR;
		File file = new File(zipDir);
		if (!file.exists()) {
			m_log.info("Creating ams zip dir: " + zipDir);
			file.mkdir();
		}
		return zipDir;
	}
	
	public static void deleteTmpDirectory() {
		try {
			// Delete tmp log file 
			String tmpLogDir = System.getenv("TMP") + AMS_TMP_DIR;
			FileUtils.deleteDirectory(new File(tmpLogDir));
			// Delete tmp zip file  
			String tmpZipDir = System.getenv("TMP") + AMS_ZIP_DIR;
			FileUtils.deleteDirectory(new File(tmpZipDir));
			
			m_log.info("Delete tmp log at " + tmpLogDir + " and " + tmpZipDir);
		} catch (Exception e) {
			m_log.error("Could not delete tmp file", e);
		}
	} 
	
	public static void zipLogFiles(String localDir, String destZipFile) {
		ZipOutputStream out = null;
		try {
			FileOutputStream dest = new FileOutputStream(destZipFile);
			CheckedOutputStream checksum = new CheckedOutputStream(dest, new Adler32());
			out = new ZipOutputStream(new BufferedOutputStream(checksum));
			byte data[] = new byte[BUFFER];
			File localFile = new File(localDir);
			List<String> populatedFiles = new ArrayList<String>();
			populateLogFiles(localFile, populatedFiles);
			for (String filePath : populatedFiles) {
				m_log.info("Adding log file " + filePath + " to " + destZipFile);
				FileInputStream fi = new FileInputStream(filePath);
				BufferedInputStream buffered = null;
				try { 
					buffered = new BufferedInputStream(fi, BUFFER);
					ZipEntry entry = new ZipEntry(filePath.substring(localFile.getAbsolutePath().length() + 1, filePath.length()));
					out.putNextEntry(entry);
					int count;
					while((count = buffered.read(data, 0, BUFFER)) != -1) {
						out.write(data, 0, count);
					}
				} catch (Exception e) {
				} finally {
					buffered.close();
				}
			}
		} catch(Exception e) {
			m_log.info("Error in compress file under " + localDir, e);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
			} catch (IOException e) {
				m_log.info("Error in closing resourse", e);
			}
		}
	}
	
	private static void populateLogFiles(File file, List<String> logFiles) {
		File[] files = file.listFiles();
		for (int i = 0; i < files.length; i++) {
			if (files[i].isFile()) {
				logFiles.add(files[i].getAbsolutePath());
			} else {
				populateLogFiles(files[i], logFiles);
			}
		}
	}
	
	public static void main(String[] args) {
		String localDir = "D:\\log";
		LogCollectorUtils.zipLogFiles(localDir , localDir + "zipfile.zip");
	}
}
